fix_ps <- function(...){
  ps <- starprep(... = ..., stat = "p")
  # Set the p-value of the intercept to 1 (no stars on the intercept)
  ps <- lapply(ps, function(x) {x[names(x) == "(Intercept)"] <- 1; x})
}

scale_dv <- function(input_vec, control_vec){
  return((input_vec - mean(control_vec, na.rm = TRUE))/sd(control_vec, na.rm = TRUE))
}

add_parens <- function(x, digits=3){
  x <- as.numeric(x)
  return(paste0("(", sprintf(paste0("%.", digits, "f"), x), ")"))
}

format_num <- function(x, digits=3){
  x <- as.numeric(x)
  return(paste0(sprintf(paste0("%.", digits, "f"), x)))
}

se_mean <- function(x){
  x_nona <- x[!is.na(x)]
  n <- length(x_nona)
  return(sd(x_nona)/(sqrt(n)))
}

weighted.var <- function(x, w, na.rm=FALSE)
  #  Computes the variance of a weighted mean following Cochran 1977 definition
{
  if (na.rm) { w <- w[i <- !is.na(x)]; x <- x[i] }
  n = length(w)
  xWbar = weighted.mean(x,w,na.rm=na.rm)
  wbar = mean(w)
  out = n/((n-1)*sum(w)^2)*(sum((w*x-wbar*xWbar)^2)-2*xWbar*sum((w-wbar)*(w*x-wbar*xWbar))+xWbar^2*sum((w-wbar)^2))
  return(out)
}

weighted_se <- function(x, w, na.rm=TRUE){
  return(sqrt(weighted.var(x = x, w = w, na.rm=na.rm)))
}

#packageurl <- "https://cran.r-project.org/src/contrib/Archive/stargazer/stargazer_5.1.tar.gz"
#install.packages(packageurl, repos=NULL, type="source")


